<template>
  <div class="furnace-main" style="background: #fff">
    <div class="add_btn_top">
      <el-button
        type="primary"
        size="mini"
        @click="createFurnace"
        v-permission="[1, 'button']"
        >创建合炉
      </el-button>
      <!-- v-permission="[21, 'button']" -->
      <el-button
        type="primary"
        size="mini"
        @click="handleReset"
        :loading="btnLoading"
        >重置</el-button
      >
    </div>
    <div class="" v-permission="[4, 'list']">
      <el-table
        :data="formulaData"
        height="100px"
        v-adaptive
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-table
              border
              size="mini"
              :data="scope.row.formula.formulaParameter[0].keys"
              style="width: 100%"
              v-if="scope.row.formula"
            >
              <el-table-column label="内容\名称" align="center">
                <template slot-scope="scope">
                  {{ scope.row }}
                </template>
              </el-table-column>
              <el-table-column
                v-for="(item, index) in scope.row.formula.formulaParameter"
                :key="index"
                :label="'阶段' + (index + 1)"
                align="center"
              >
                <template slot-scope="scope">
                  {{ item.texts[scope.$index] }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="45"> </el-table-column>
        <el-table-column
          width="55"
          type="index"
          :index="indexMethod"
          label="序号"
        ></el-table-column>
        <el-table-column
          prop="furnaceCode"
          label="熔炼炉代号"
          width="90"
        ></el-table-column>
        <el-table-column
          prop="batchNumber"
          label="批次号"
          width="100"
        ></el-table-column>
        <!-- <el-table-column prop="partNumber" label="零件号"></el-table-column>
        <el-table-column prop="partName" label="零件名称"></el-table-column> -->
        <!-- <el-table-column
          prop="processNumber"
          label="工序号"
        ></el-table-column>
        <el-table-column prop="processName" label="工序名称"></el-table-column> -->
        <el-table-column
          prop="specificationNumber"
          label="工艺规程编号"
          width="110"
        ></el-table-column>
        <el-table-column label="设备信息" width="90">
          <template slot-scope="scope">
            <div
              v-if="
                scope.row.formula &&
                scope.row.formula.deviceInfoList &&
                scope.row.formula.deviceInfoList.length == 1 &&
                scope.row.formula.deviceInfoList[0].deviceList.length == 0
              "
            >
              <el-button :disabled="true" slot="reference" type="mini"
                ><i class="el-icon-view" style="margin-right: 3px"></i
                >无设备</el-button
              >
            </div>
            <div v-else>
              <el-popover
                placement="bottom"
                width="200"
                trigger="click"
                v-if="
                  scope.row.formula &&
                  scope.row.formula.deviceInfoList.length !== 0
                "
              >
                <ul
                  class="el-select-group__wrap"
                  v-for="(deviceInfo, index) in scope.row.formula
                    .deviceInfoList"
                  :key="index"
                >
                  <li class="el-select-group__title" style="padding-left: 10px">
                    {{ deviceInfo.deviceTypeName }}
                  </li>
                  <li>
                    <ul class="el-select-group">
                      <li
                        class="el-select-dropdown__item"
                        v-for="(device, index) in deviceInfo.deviceList"
                        :key="index"
                      >
                        <span>{{ device.deviceName }}</span>
                      </li>
                    </ul>
                  </li>
                </ul>
                <p
                  v-if="
                    !scope.row.formula ||
                    scope.row.formula.deviceInfoList.length == 0
                  "
                >
                  无数据
                </p>
                <el-button slot="reference" type="mini"
                  ><i class="el-icon-view" style="margin-right: 3px"></i
                  >设备</el-button
                >
              </el-popover>
              <el-button :disabled="true" slot="reference" type="mini" v-else
                ><i class="el-icon-view" style="margin-right: 3px"></i
                >无设备</el-button
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit"> </el-table-column>
        <el-table-column
          v-for="(item, index) in otherLabels"
          :key="index"
          :label="item"
        >
          <template slot-scope="scope">
            {{ formatLabelData(scope.row.formula, item) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="partTotalNumber"
          label="来件数量"
        ></el-table-column>
      </el-table>
      <Pagination
        @pagination="pagination"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="pageSize"
        :pageSizes.sync="pageSizes"
      />
    </div>
    <el-drawer
      title="合炉"
      :visible.sync="showDrawer"
      direction="rtl"
      size="20%"
      :show-close="true"
      :wrapperClosable="false"
    >
      <div class="check_data">
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="ProcessType" border>工艺类型</el-checkbox>
          <el-checkbox label="PartType" border>零件类型</el-checkbox>
          <el-checkbox label="materialMark" border>材料牌号</el-checkbox>
          <el-checkbox label="Temperature" border>设定温度</el-checkbox>
          <el-checkbox label="HoldingTime" border>保温时间</el-checkbox>
          <el-checkbox label="DeviceType" border>设备类型</el-checkbox>
          <el-checkbox label="Device" border>设备</el-checkbox>
          <el-checkbox label="ControlStrategy" border>控制策略</el-checkbox>
        </el-checkbox-group>
        <div class="drawer_footer">
          <el-button
            type="primary"
            size="mini"
            style="width: 50%; z-index: 99"
            @click="handleSubmit"
            >提 交</el-button
          >
          <!-- <el-button size="mini" style="width: 50%" @click="handleClose"
            >取 消</el-button
          > -->
          <el-button size="mini" style="width: 50%" @click="handleRes"
            >重 置</el-button
          >
        </div>
      </div>
    </el-drawer>
    <FurnaceDialog
      :taskIdList="selectionIds"
      @handleClose="handleCloseFurnace"
      :show="furnaceDialogShow"
    ></FurnaceDialog>
  </div>
</template>

<script>
import Pagination from "@/views/common/page";
import { KEY_ATT } from "@/utils/local";
import { formulaDel, taskDel, formulaList } from "@/api/assets";
import { getTasks } from "@/api/productionTask";
import { Loading } from "element-ui";
import FurnaceDialog from "./components/FurnaceDialog/index.vue";
import { tasks2formula } from "@/api/technology";
export default {
  components: {
    Pagination,
    FurnaceDialog,
  },

  data() {
    return {
      furnaceDialogShow: false,
      btnLoading: false,
      pageNum: 1,
      pageSize: 20,
      pageSizes: [20, 50, 100, 300],
      total: 7,
      showDrawer: false,
      checkList: [],
      selectionIds: [],
      otherLabels: KEY_ATT,
      formulaData: [],
    };
  },
  mounted() {
    this.getfurnaceTaskData();
  },
  methods: {
    handleCloseFurnace() {
      this.furnaceDialogShow = false;
    },
    handleRes() {
      this.checkList = [];
    },
    delList() {
      return new Promise((resolve) => {
        var that = this;
        var params = {
          page: 1,
          pageSize: 0,
          rnb: Date.parse(new Date()),
          includeDeviceType: false,
          includeFormula: false,
        };
        getTasks(params).then((r) => {
          const tasksTokens = r.data.results.map((item) => item.token);
          formulaList().then((res) => {
            const formulasTokens = res.data.results.map((item) => item.token);
            resolve({
              tasksTokens,
              formulasTokens,
            });
          });
        });
      });
    },
    async handleReset() {
      this.$confirm("是否确认重置吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        this.btnLoading = true;
        this.$msg("重置中,请稍等!!");
        const tokens1 = await this.delList();
        let arr = [];
        tokens1.formulasTokens.forEach((item, index) => {
          arr.push(
            new Promise((resolve, reject) => {
              // 执行删除
              formulaDel(item).then((res) => {
                resolve(true);
              });
            })
          );
        });
        tokens1.tasksTokens.forEach((item, index) => {
          arr.push(
            new Promise((resolve, reject) => {
              // 执行删除
              taskDel(item).then((res) => {
                resolve(true);
              });
              resolve(true);
            })
          );
        });
        //循环全部结束后执行
        Promise.all(arr)
          .then((result) => {
            this.$msg({
              message: "重置成功!",
              type: "success",
            });
            console.log("删除成功", arr);
          })
          .finally((f) => {
            this.btnLoading = false;
            this.getfurnaceTaskData();
          });
      });
    },
    pagination({ page, limit }) {
      this.pageNum = page;
      this.pageSize = limit;
      this.getfurnaceTaskData();
    },
    indexMethod(index) {
      return index + 1;
    },
    initTechnologyParameter() {
      var labels = [];
      this.formulaData.forEach((item1) => {
        if (item1.formula) {
          item1.formula.technologyParameter.forEach((item2) => {
            if ($.inArray(item2.key, labels) == -1) {
              labels.push(item2.key);
            }
          });
        }
      });
      // this.otherLabels = labels;
      console.log(" :>> ", this.otherLabels, "KE", KEY_ATT);
    },
    formatLabelData(data, label) {
      if (data) {
        var technologyParameterData = data.technologyParameter;
        for (let i = 0; i < technologyParameterData.length; i++) {
          if (technologyParameterData[i].key == label) {
            return technologyParameterData[i].value;
          }
        }
      }
    },
    //获取合炉任务列表
    getfurnaceTaskData() {
      var that = this;
      that.loading = true;
      var params = {
        page: that.pageNum,
        pageSize: that.pageSize,
        rnb: Date.parse(new Date()),
        includeDeviceType: true,
        includeFormula: true,
        includeChildren: true,
      };
      getTasks(params).then((res) => {
        that.total = res.data.numResults;
        that.formulaData = res.data.results;
      });
    },
    //创建合炉
    createFurnace() {
      if (this.selectionIds.length == 0) {
        this.$msg("请选择合炉数据");
        return;
      }
      this.furnaceDialogShow = true;

      // this.showDrawer = true;
    },
    //选中值
    handleSelectionChange(val) {
      this.selectionIds = [];
      val.forEach((element) => {
        this.selectionIds.push(element.id);
      });
    },
    //提交
    async handleSubmit() {
      let loadingInstance = "";
      this.$confirm("创建合炉,历史合炉配方将清空!", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        var that = this;

        that.loading = true;
        loadingInstance = Loading.service({
          text: "创建合炉中,请稍等",
        });
        var params = {
          taskIdList: that.selectionIds,
          filterList: that.checkList,
        };
        // var params = {
        //   page: that.pageNum,
        //   pageSize: that.pageSize,
        //   rnb: Date.parse(new Date()),
        //   includeDeviceType: true,
        //   includeFormula: true,
        // };
        const tokens1 = await this.delList();
        let arr = [];
        tokens1.formulasTokens.forEach((item, index) => {
          arr.push(
            new Promise((resolve, reject) => {
              // 执行删除
              formulaDel(item).then((res) => {
                resolve(true);
              });
            })
          );
        });
        //循环全部结束后执行
        Promise.all(arr)
          .then((result) => {
            tasks2formula(params)
              .then((res) => {
                that.$message.success("操作成功");
                this.$router.push("furnaceRecipeList");
                that.showDrawer = false;
              })
              .finally((f) => {
                that.loading = false;
                that.$nextTick(() => {
                  // 以服务的方式调用的 Loading 需要异步关闭
                  loadingInstance.close();
                });
              });
          })
          .finally((f) => {})
          .catch((err) => {
            that.showDrawer = false;
            that.loading = false;
            this.$nextTick(() => {
              // 以服务的方式调用的 Loading 需要异步关闭
              loadingInstance.close();
            });
          });
      });
    },
    //取消
    handleClose() {
      this.showDrawer = false;
    },
  },
};
</script>

<style lang='scss' scoped>
@import "~@/styles/mixin.scss";
.furnace-main {
  /deep/ .el-drawer__header {
    margin-bottom: 10px;
  }
}
/* .check_data {
  margin-left: 20px;
  /deep/ .el-checkbox {
    width: 95%;
    margin-top: 20px;
  }
  /deep/ .el-checkbox.is-bordered + .el-checkbox.is-bordered {
    margin-left: 0;
  }
} */

.drawer_footer {
  padding: 0 20px;
  width: 100%;
  position: absolute;
  bottom: 19px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  left: 0;
}
</style>
